﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using DaInterFace;
using Newtonsoft.Json;

namespace DaFunction.PDA
{
    internal class PDASerialApi : ISerialApi
    {
        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="obj">对象</param>
        /// <returns></returns>
        public string Serializer(Type type, object obj, SerialType serialtype)
        {
            String retStr = "";
            switch (serialtype)
            {
                case SerialType.Xml:
                    MemoryStream Stream = new MemoryStream();
                    XmlSerializer xml = new XmlSerializer(type);
                    try
                    {
                        //序列化对象
                        xml.Serialize(Stream, obj);
                        Stream.Position = 0;
                        StreamReader sr = new StreamReader(Stream);
                        retStr = sr.ReadToEnd();
                        sr.Dispose();
                    }
                    catch (InvalidOperationException)
                    {
                        //throw;
                    }

                    Stream.Dispose();
                    break;
                case SerialType.Json:
                    retStr = JsonConvert.SerializeObject(obj);
                    break;
            }

            return retStr; 
        }
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="xml">XML字符串</param>
        /// <returns></returns>
        public object Deserialize(Type type, string str, SerialType serialtype)
        {
            Object obj = null;
            switch (serialtype)
            {
                case SerialType.Xml:
                    try
                    {
                        using (StringReader sr = new StringReader(str))
                        {
                            XmlSerializer xmldes = new XmlSerializer(type);
                            obj = xmldes.Deserialize(sr);
                        }
                    }
                    catch (Exception e)
                    {

                    }
                    break;
                case SerialType.Json:
                    obj = JsonConvert.DeserializeObject(str, type);
                    break;
            }

            return obj;
        }
    }
}
